package com.small.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @create: xie
 */
@Slf4j
public class CookieUtil {

    private static final String COOKIE_DOMIN="xie.com";
    private static final String COOKIE_NAME="mmall_login_token";
    public static String readLoginToken(HttpServletRequest request){
        Cookie[] cookies=request.getCookies();
        if (cookies!=null){
            for(Cookie ck:cookies){
                if(StringUtils.equals(ck.getName(),COOKIE_NAME)){
                    log.info("read cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
                    return ck.getValue();
                }
            }
        }
        return null;
    }

    //生成登录cookie
    public static void writeLoginToken(HttpServletResponse response,String token){
        Cookie cookie=new Cookie(COOKIE_NAME,token);
        cookie.setDomain(COOKIE_DOMIN);
        cookie.setHttpOnly(true);
        cookie.setPath("/");//代表设置在根目录

        //单位是秒，如果不设置cookie就不会写入硬盘，而是写在内存。只在当前页面有效
        cookie.setMaxAge(-1);//如果是-1表示永久
        log.info("write cookieName:{},cookieValue:{}",cookie.getName(),cookie.getValue());
        response.addCookie(cookie);
    }

    public static void delLoginToken(HttpServletResponse response,HttpServletRequest request){
        Cookie[] cks=request.getCookies();
        if(cks!=null){
            for(Cookie ck:cks){
                if(StringUtils.equals(ck.getName(),COOKIE_NAME)){
                    ck.setDomain(COOKIE_DOMIN);
                    ck.setPath("/");
                    ck.setMaxAge(0); //设置成0表示删除此cookie
                    log.info("del cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
                    response.addCookie(ck);
                }
            }
        }
    }
}
